/**
*	reim_node版本的服务端
*	开发者：雨中磐石(rainrock)
*	网址：http://www.rockoa.com/
*	时间：2019-08-17
*/


function rockREIMServer(conf){
	var me = this;
	this.rockBase = false;
	this.config	  = {};
	for(var i in conf)this[i] = conf[i];
	
	
	this.run = function(){
		this.startreimserver();
	};
	
	this.startreimserver= function(){
		this.wsclients	= {};
		this.daicheck	= [];
		this.taskurla	= {};
		var stra		= this.config.recid.split(',')
		this.recIDArr	= [];
		for(var i=0;i<stra.length;i++){
			this.recIDArr.push(stra[i]);
			this.recIDArr.push(stra[i]+'_app');
		}
		
		const WebSocket = require('ws');
		
		//是否使用ssl的
		if(this.config.ssl_open && this.config.ssl_key && this.config.ssl_cert){
			var https	= require('https');
			var server=https.createServer({
				key: this.rockBase.getFsobj().readFileSync(this.config.ssl_key),
				cert: this.rockBase.getFsobj().readFileSync(this.config.ssl_cert),
				passphrase:this.config.ssl_pass
			}, function (req, res) {
				res.writeHead(403);
				res.end('reimService WebSockets Success '+me.rockBase.now('now')+'\n');
			}).listen(me.config.port);
			var wss 		= new WebSocket.Server({
				server: server
			});
			this.rockBase.debug('reimservice start success wss://'+me.config.ip+':'+me.config.port+'');
		}else{
			var wss 		= new WebSocket.Server({
				'port': this.config.port,
				'host': this.config.ip,
				'verifyClient':this.verifyClient
			},function(){
				me.rockBase.debug('reimservice start success listening:'+me.config.ip+':'+me.config.port+'');
			});
		}
		
		//客户端连接
		wss.on('connection', function connection(ws, req) {
			ws.on('message', function incoming(message){
				me.wsonmessage(this, message);
			});
			ws.on('close', function incoming(code){
				me.wsonclose(this);
			});
		});
	}
	
	/**
	*	验证是否可以连接
	*/
	this.verifyClient=function(info){
		var headers,cookie,origin,useragent;
		headers		= info.req.headers;
		cookie 		= headers.cookie;
		origin 		= headers.origin; 
		useragent 	= headers['user-agent'];
		var cori	= me.config.origin,bo,i;
		if(cori && cori!='*'){
			bo = false;
			var coria = cori.split(',');
			for(i=0;i<coria.length;i++){
				if(origin.indexOf(coria[i])>-1){
					bo = true;
					break;
				}
			}
			if(!bo){
				me.rockBase.debug('linkerr:'+origin+' not in('+cori+')');
				return false;
			}
		}
		return true;
	}
	
	this.inrecID=function(fr){
		var i=0,len = this.recIDArr.length;
		for(i=0;i<len;i++){
			if(this.recIDArr[i]==fr)return true;
		}
		return false;
	};
	
	//通过6553端口推送过来的信息
	this.wsreimpush = function(d){
		var fr = d.from,atype=d.atype;
		if(!fr || !atype || !this.inrecID(fr))return '';
		var barr = '';
		if(atype=='send'){
			barr = this.sendmsg(fr, d.receid, d);
		}
		
		if(atype=='starttask'){
			this.starttask(fr,d.url,true);
		}
		if(atype=='runurl'){
			var url = d.url;
			if(url)this.rockBase.runurl(url);
		}
		if(atype=='sendapp'){
			var nfr = this.getfromid(fr);
			barr = this.sendmsgs(nfr+'_app', d.receid, d);
		}
		if(atype=='getonline'){
			var nfr = this.getfromid(fr);
			barr = {
				pc:this.getonlineuid(nfr,d.onlineid),
				app:this.getonlineuid(nfr+'_app',d.onlineid)
			}
		}
		return barr;
	}
	
	/**
	*	收到信息
	*/
	this.wsonmessage=function(ws, msg){
		var msg		= msg.toString();
		this.rockBase.debug(msg);
		var da 		= JSON.parse(msg);
		var atype 	= da.atype,fr=da.from,barr='';
		if(!fr || !atype || !this.inrecID(fr)){
			ws.close();
			return '';
		}
		
		//首次连接
		if(atype=='connect'){
			ws.adminid  	= da.adminid;
			ws.adminname  	= da.sendname;
			ws.recefrom  	= fr;
			var ows			= this.getclient(fr, da.adminid);
			if(ows){
				this.wssend(ows,{
					'type'	: 'offoline',
					'sendid': da.adminid
				}); //告诉原来在别的地方登录
			}
			this.wsclients[fr][da.adminid] = ws;
		}
		
		if(!this.wsclients[fr])ws.close();
		
		//获取在线人员
		if(atype=='getonline'){
			barr = this.getonlineuid(fr);
			this.wssend(ws,{
				'type'	: 'getonline',
				'online': barr,
			});
		}
		
		//发消息
		if(atype=='send'){
			barr = this.sendmsg(fr, da.receid, msg);
		}
		
		//运行地址
		if(atype=='runurl'){
			if(da.url)this.rockBase.runurl(da.url);
		}
		
		return barr;
	}
	
	//获取初始fromid
	this.getfromid=function(fr){
		return fr.replace('_app','');
	}
	
	/**
	*	发消息
	*/
	this.sendmsg=function(fr,receid, msg){
		var barr = {};
		if(!fr || !receid)return false;
		var nfr = this.getfromid(fr);
		barr['pc'] = this.sendmsgs(nfr,receid, msg);
		return barr;
	}
	this.sendmsgs=function(fr,receid, msg){
		receid	  = ''+receid+'';
		var wsobj = this.wsclients[fr],uid,i,ws,reca;
		if(!wsobj){
			wsobj = {};
			this.wsclients[fr]={};
		}
		var zshu = 0,yfuid='',wfuid='';
		if(receid=='all'){
			for(uid in wsobj){
				ws = wsobj[uid];
				if(ws){
					this.wssend(ws, msg);
					zshu++;
					yfuid+=','+uid+'';
				}else{
					wfuid+=','+uid+'';
				}
			}
		}else{
			reca = receid.split(',');
			for(i=0;i<reca.length;i++){
				uid = reca[i];
				ws  = wsobj[uid];
				if(ws){
					this.wssend(ws, msg);
					zshu++;
					yfuid+=','+uid+'';
				}else{
					wfuid+=','+uid+'';
				}
			}
		}
		if(yfuid!='')yfuid=yfuid.substr(1);//已发uid
		if(wfuid!='')wfuid=wfuid.substr(1);//未发uid
		return {
			zshu:zshu,
			yfuid:yfuid,
			wfuid:wfuid
		};
	}
	
	/**
	*	下线
	*/
	this.wsonclose = function(ws){
		var fr = ws.recefrom;
		if(!this.wsclients[fr])this.wsclients[fr]={};
		this.wsclients[fr][ws.adminid] = false;
		this.rockBase.debug('close:'+ws.adminid+':'+ws.adminname+'');
	}
	
	this.getclient = function(fr, uid){
		if(!this.wsclients[fr])this.wsclients[fr]={};
		return this.wsclients[fr][uid];
	}
	
	/**
	*	发送
	*/
	this.wssend = function(ws, sst){
		if(typeof(sst)=='object')sst = JSON.stringify(sst);
		ws.send(sst);
	}
	
	/**
	*	获取在线人员id
	*/
	this.getonlineuid=function(fr, oid){
		var s 	  = '',uid;
		var wsobj = this.wsclients[fr];
		if(!wsobj)return s;
		if(oid && oid!='all'){
			oid	= ''+oid+'';
			var oida = oid.split(','),i;
			for(i=0;i<oida.length;i++)if(wsobj[oida[i]])s+=','+oida[i]+'';
		}else{
			for(uid in wsobj)if(wsobj[uid])s+=','+uid+'';
		}
		if(s!='')s=s.substr(1);
		return s;
	}
}

module.exports = rockREIMServer;